import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 读取csv文件
df = pd.read_csv('insurance.csv')

# 将分类变量转化为数值变量
df['sex'] = df['sex'].map({'female': 0, 'male': 1})
df['smoker'] = df['smoker'].map({'yes': 1, 'no': 0})
df['region'] = df['region'].map({'southwest': 0, 'southeast': 1, 'northwest': 2, 'northeast': 3})

# 定义因变量和自变量
X = df[['age', 'sex', 'bmi', 'children', 'smoker']]
y = df['charges']

# 对数据进行训练集和测试集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 对数据进行线性回归建模
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# 预测测试集结果
y_pred = regressor.predict(X_test)

# 输出模型细节和性能指标
print(f'模型的系数：{regressor.coef_}')
print(f'模型的截距：{regressor.intercept_}')
print(f'模型的R^2值：{r2_score(y_test, y_pred)}')  # R^2值越接近1，模型的拟合度越好
print(f'模型的均方误差：{mean_squared_error(y_test, y_pred)}')